import router from '@/router';
import axios from "axios";
import {Message} from "element-ui";
import Storage from "@/js/storage.js"
import systemConfig from "@/system.config.js";
import kunUtil from "@/js/kunUtil.js";
import {emitEvent} from "@/js/EventBus.js";


let axiosConfig = {
    baseURL: systemConfig.baseUrl,
    // 超时时间
    timeout: 10 * 1000,
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    },
    responseType: 'json'
}
let instance = axios.create(axiosConfig);


instance.interceptors.request.use(config => {
    // console.log("start request",config)
    let requestUrl = config.url;
    requestUrl = requestUrl.split('?')[0];
    // 请求接口在白名单内，则无需登录获得的JWT
    if (systemConfig.whiteList.includes(requestUrl)) {
        return config;
    }

    // 不在白名单内，需要登录获得的JWT，如果没有登录提示请先登录
    if (!kunUtil.isLogin()) {
        return Promise.reject("Unauthorized");
    }

    config.headers.Authorization = "KunTools_token " + Storage.get("token");
    return config;
}, error => {
    console.log('request err:' + error)
    return Promise.reject(error);
});


instance.interceptors.response.use(response => {
    let res = response.data;
    // console.log(res)

    switch (res.status) {
        case 200:
            return response;
        case 401:
            Message.error("登录已失效");
            Storage.remove("token");
            setTimeout(() => {
                if (kunUtil.judgeUserType() === systemConfig.userType.ADMIN) {
                    // 管理员登录失效,跳转到登录路由/kun
                    router.push('/kun');
                } else {
                    // 用户登录失效,跳转到首页/index
                    router.push('/');
                    emitEvent("showLogin", {from: "登录已失效!"})
                }
            }, 1000);

            return Promise.reject(response);
        case 500:
            Message.error(response.data.message);
            return Promise.reject(response);
        default:
            return response;
    }

}, error => {
    // 对响应错误做点什么
    // console.log('response err:' + error)
    if (error === "Unauthorized") {
        return Promise.reject("请求时没有JWT，请先登录！")
    }

    let {message} = error;
    if (message === "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = `系统接口${message.substr(message.length - 3)}异常`;
    }
    Message.error(message);
    return Promise.reject(error)
});


export default instance
